package san.web.system;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.security.domain.Resource;
import com.security.domain.Role;
import com.utils.CollectionUtils;
import com.utils.Page;
import com.web.struts2.CRUDSupportAction;

/**
 * 角色管理Action.
 * 
 * @see CRUDActionSupport
 * @author san
 */
@ParentPackage("default")
@Results( { @Result(name = "reload", location = "role.shtml", type = "redirect") })
public class RoleAction extends CRUDSupportAction {

	private static final long serialVersionUID = 8517636900960039101L;

	private List<Role> allRoles;

	private Role role;

	private List<Resource> allResource;
	private Page<Role> page = new Page<Role>(10);// 每页10条记录

	@SuppressWarnings("unchecked")
	@Override
	protected void prepareModel() throws Exception {
		if (role != null && StringUtils.isNotBlank(role.getId())) {
			role = userService.getRole(role.getId());
		} else {
			if (StringUtils.isNotBlank(getId())) {
				role = userService.getRole(getId());
				setIds(CollectionUtils.fetchPropertyToList(role.getResources(),
						"id"));
			} else {
				role = new Role();
			}
		}
	}

	@Override
	public String list() throws Exception {
		page = userService.getAllRoles(page);
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String input() throws Exception {
		allResource = userService.getAllResources();
		return INPUT;
	}

	@SuppressWarnings("finally")
	@Override
	public String save() throws Exception {
		try {
			userService.saveRole(role, ids);
			addActionMessage("保存角色成功!");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError("保存角色失败!");
		} finally {
			return RELOAD;
		}
	}

	@SuppressWarnings("finally")
	@Override
	public String delete() throws Exception {
		try {
			userService.deleteRole(getId());
			addActionMessage("删除角色成功!");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError("删除角色失败!");
		} finally {
			return RELOAD;
		}
	}

	public void setAllRoles(List<Role> allRoles) {
		this.allRoles = allRoles;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public List<Role> getAllRoles() {
		return allRoles;
	}

	public Role getRole() {
		return role;
	}

	public List<Resource> getAllResource() {
		return allResource;
	}

	public void setAllResource(List<Resource> allResource) {
		this.allResource = allResource;
	}

	public Page<Role> getPage() {
		return page;
	}

	public void setPage(Page<Role> page) {
		this.page = page;
	}

}